var model = require('../../../model/model.js')
var netWork = require('../../../utils/netWork.js');
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const log = require('../../../utils/logs.js');
const QR = require('../../../utils/weapp-qrcode.js')
const regeneratorRuntime = require('../../../utils/runtime');
var Base64 = require('../../../utils/base64.js');
import {isShowReminderOfExpired} from "../../../utils/publicMethods";
var isClick = true;
var bobing = require('../../../utils/bobing.js');
//选择城市
var show = false;
var addressInfo = {};
var item = {};
var popup = require('../../../utils/popupUtils.js');
import {requestSubscribeMessage} from "../../../utils/wxapi";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imagesUrl: getApp().globalData.imagesUrl,
        topHeight: 0,
        ani: 0, //动画是否执行
        top: 0,
        height: 529,
        isShowQRcode: false, //核销礼券页面
        isShowPrizes: false, //抽奖成功，显示领取成功页面
        isLoading: false,
        materialInfo: {}, //邮寄信息
        address: '请选择地区', //地区文字显示
        item: { //城市选择器信息
            show: show
        },
        addressMsg: '', //详细地址
        formValue: {}, //form表单邮寄信息
        isShowEntityPopup: false, //是否显示实物弹窗
        redEnvelopes: 0, //红包
        entityData: {}, //实物弹窗奖励信息
        isShowCouponPopup: false, //是否显示卷弹窗
        couponType: 0, //卷弹窗的卷类型
        couponPrizeInfo: {}, //卷弹窗的奖励信息
        isShowEntityTips: false, //实物领取成功提示
        handPrizeId: "", //已经显示过小手提示的奖励id
        commonHeight: 0,
        tanban_big_bg: getApp().globalData.imagesUrl + '/jingdianPage/tanban_big_bg.png',
        pic_btn_bg: '', //普通
        pic_bg: '', //普通
        benefitCardPopupImg: getApp().globalData.imagesUrl + '/jingdianPage/tanban_Small_bg.png',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this;
        let query = wx.createSelectorQuery();
        query.select('.logo-view').boundingClientRect(rect => {
            let clientWidth = rect.width;
            let ratio = 750 / clientWidth;
            let clientTop = rect.top;
            let top = clientTop * ratio;

            that.setData({
                top: top / 2 - top + 70
            })
            console.log(top);
            console.log(that.data.top)

        }).exec();
        //高度处理
        let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
        let prizeList = wx.getStorageSync('prizeList');
        let isLuckyBoBing = wx.getStorageSync('isLuckyBoBing');
        if (!isLuckyBoBing) {
            for (let item of prizeList) {
                if (item.boBingOrder) {
                    wx.setStorageSync('isLuckyBoBing', true);
                    break;
                }
            }
        }
        this.setData({
            qrcode: wx.getStorageSync('qrCode'),
            topHeight: topHeight,
            goToganguo: wx.getStorageSync('goToganguo'),
            prizeList: prizeList,
            qrcodeBigURL: '',
            icon: wx.getStorageSync('productType') == 4 ? 'xinyouranPage/loading_logo' : 'common/loading'
        });
        let m = wx.getStorageSync('materialInfo');
        if (m) {
            this.setData({
                materialInfo: m,
                address: m.receiveProvinceName + ' ' + m.receiveCityName + ' ' + m.receiveDistrictName,
                color: true,
                addressMsg: m.receiveAddress
            })
            addressInfo = this.data.materialInfo;
        } else {
            let userPhone = wx.getStorageSync('userPhone');
            let m1 = {};
            if (userPhone != "" && userPhone != null && userPhone != undefined) {
                m1['receivePhone'] = userPhone;
            }
            this.setData({
                materialInfo: m1
            })
        }
        //判断是否显示权益卡进度条
        this.selectComponent('#benefitCardSpeed').isShow();
        //判断是否显示弹窗
        popup.isShowTypePope(prizeList, this, getApp().globalData.popupTypes);
    },
    isLoading(isLoading, loadingText) {
        this.setData({
            isLoading: isLoading,
            loadingText: loadingText
        })

    },
    returnIndex() {
        wx.removeStorageSync('isShowPrizes');
        wx.removeStorageSync('prizeList');
        wx.redirectTo({
            url: '../index/index?oper=close',
        })
    },
    scanQcord: function () {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        api.scanCode();
    },
    showMore: function () {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        wx.navigateToMiniProgram({
            appId: api.thirdAppId,
            envVersion: getApp().globalData.ganguoAppidStyle
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function (e) {
        var that = this;
        //请求数据
        model.updateAreaData(that, 0, e);
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        setTimeout(() => {
            // 根据文档，先创建一个SelectorQuery对象实例
            let query = wx.createSelectorQuery().in(this);
            // 选择器的语法与jQuery语法相同
            query.select('.main').boundingClientRect();
            query.select('.logo-view').boundingClientRect();
            query.select('.bigPrize').boundingClientRect();
            query.select('.record-title').boundingClientRect();
            query.select('.bottomBtn').boundingClientRect();
            // 执行上面所指定的请求，结果会按照顺序存放于一个数组中，在callback的第一个参数中返回
            query.exec((res) => {
                let mainHeight = res[0].height;
                let logoViewHeight = res[1].height;
                let bigPrizeHeight = res[2].height;
                let recordTitleHeight = res[3].height;
                let bottomBtnHeight = res[4].height;
                let succBoxHeight = 140 * wx.getSystemInfoSync().windowWidth / 750;
                let height = mainHeight - logoViewHeight - bigPrizeHeight - recordTitleHeight - bottomBtnHeight;
                let mHeight = logoViewHeight + bigPrizeHeight + recordTitleHeight + bottomBtnHeight + height;
                if (mHeight <= mainHeight) {
                    let viewTotalHeight = this.data.prizeList.length * succBoxHeight + this.data.prizeList.length * 10 + 10;
                    let h = viewTotalHeight >= height ? height : viewTotalHeight;
                    this.setData({
                        commonHeight: h
                    })
                }
            })
        }, 1000);
    },

    /**
     * 显示活动规则
     */
    showRule: function () {
        wx.navigateTo({
            url: '../ruleh5/ruleh5'
        })
    },

    //将base64图片转网络图片
    sendCode(code) {
        let qrcode = code.replace(/\. +/g, '').replace(/[\r\n]/g, '')
        /*code是指图片base64格式数据*/
        //声明文件系统
        const fs = wx.getFileSystemManager();
        //随机定义路径名称
        var times = new Date().getTime();
        var codeImg = wx.env.USER_DATA_PATH + '/' + times + '.png';
        return new Promise((resolve, reject) => {
            //将base64图片写入
            fs.writeFile({
                filePath: codeImg,
                data: qrcode.slice(22),
                encoding: 'base64',
                success: () => {
                    resolve(codeImg)
                }
            });
        })

    },
    async createCanvvasImage() {
        wx.showLoading({
            title: '正在保存...',
        })
        const that = this;
        let ticketNo = "【券号】" + this.data.ticket.FTicketNo; //累计金额
        let time = "【有效期】" + this.data.ticket.FBeginDate + "至" + this.data.ticket.FEndDate; //称号
        let rule1 = "1." + this.data.ticket.FConsumeRule;
        let rule2 = "2." + this.data.ticket.FUseRule
        //背景图
        let headImg = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/successNew/qr_bg_cj.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        //标题
        let titleImgLeft = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/qrcode/ticket_title_l.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        let titleImgRight = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/qrcode/ticket_title_r.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        let kfImg = new Promise(function (resolve) {
            wx.getImageInfo({
                src: that.data.imagesUrl + '/qrcode/kf.png',
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });
        let qrcodeUrl = await that.sendCode(that.data.qrcodeBigURL);
        //qrcode
        let qrcode = new Promise(function (resolve) {
            wx.getImageInfo({
                src: qrcodeUrl,
                success: function (res) {
                    resolve(res.path)
                },
                fail: function (err) {
                    console.log(err)
                    wx.showToast({
                        title: '网络错误请稍后重试',
                        icon: 'loading'
                    })
                }
            })
        });

        Promise.all([headImg, qrcode, titleImgLeft, titleImgRight, kfImg]).then(function (result) {
            const ctx = wx.createCanvasContext('myCanvas');
            let height = 0; //当前高度
            //背景图
            ctx.drawImage(result[0], 20, 50, 580, 880);
            //临时保存
            ctx.restore();
            //  //二维码
            // ctx.drawImage(result[2], 153, 90, 25, 19);
            ctx.font = 'normal bold 33px Source Han Sans CN';
            ctx.setFillStyle("#B72733"); // 文字颜色
            ctx.setTextAlign("center"); //居中
            ctx.fillText(that.data.ticketName, 310, 120); // 绘制文字
            //二维码
            if (that.data.ticket.FSource == '001') {
                ctx.drawImage(result[1], 190, 160, 250, 250);
            } else {
                ctx.drawImage(result[4], 190, 160, 250, 250);
            }
            //临时保存
            ctx.restore();
            ctx.font = 'normal bold 18px Source Han Sans CN';
            ctx.setFillStyle("#231815"); // 文字颜色
            ctx.setTextAlign("center"); //居中
            ctx.fillText(ticketNo, 300, 470); // 绘制文字
            //临时保存
            ctx.restore();
            ctx.fillText(time, 300, 510); // 绘制文字
            //临时保存
            ctx.restore();

            ctx.font = 'normal bold 18px Source Han Sans CN';
            ctx.setFillStyle("#231815"); // 文字颜色
            ctx.setTextAlign("left");
            ctx.fillText("使用规则:", 90, 570); // 绘制文字
            // //临时保存
            ctx.restore();

            var text = that.data.ticket.FNote;
            // console.log(text)
            var temp = text.split(/[\n,]/g);
            var heights = 610;
            // for(var i =0;i<temp.length;i++){

            // var he = that.drawText(ctx,temp[0],100, heights, heights,432) // 自动
            //heights =he+heights;
            // console.log(temp[i]);
            ctx.restore();
            that.drawText(ctx, temp, 90, heights, heights, 440); // 自动

            ctx.restore();

            // }
            // console.log(he+"he")
            //ctx.draw()
            // ctx.fillText(rule1, 100, 630); // 绘制文字
            //  //临时保存
            //  ctx.restore();
            // ctx.fillText(rule2, 100, 660); // 绘制文字 
            // // //临时保存
            // ctx.restore();
            // ctx.setFillStyle("#bd2f2f"); // 文字颜色
            // ctx.fillText("3.请保存上方二维码，结款时出示给商家！", 100, 690); // 绘制文字
            // //  //临时保存
            //  ctx.restore();
            // ctx.setFillStyle("#231815"); // 文字颜色
            // ctx.fillText("若是实物奖品，请在餐中联系商家兑付，结款时", 100, 720); // 绘制文字
            // ctx.fillText("出示二维码核销该奖品！", 100, 750); // 绘制文字




            let canvasToTempFilePath = "";
            ctx.draw(false, function () {
                // canvas画布转成图片并返回图片地址
                console.log(111)
                wx.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    success: function (res) {
                        // console.log(res.tempFilePath)
                        canvasToTempFilePath = res.tempFilePath
                        that.setData({
                            showShareImg: true
                        })
                        console.log(res.tempFilePath, 'canvasToTempFilePath')
                        console.log("绘制成功");
                        that.saveShareImg(canvasToTempFilePath);
                    },
                    fail: function () {
                        wx.showToast({
                            title: '绘制失败',
                        })
                    },
                    complete: function () {
                        wx.hideLoading()
                        wx.hideToast()
                    }
                })
            })

        })

    },
    drawText: function (ctx, context, leftWidth, initHeight, titleHeight, canvasWidth) {
        //  console.log(str)

        for (var i = 0; i < context.length; i++) {
            var str = context[i];
            var lineWidth = 0;
            var lastSubStrIndex = 0; //每次开始截取的字符串的索引
            ctx.font = 'normal bold 18px Source Han Sans CN';
            ctx.setFillStyle("#231815"); // 文字颜色
            ctx.setTextAlign("left");

            for (let i = 0; i < str.length; i++) {
                lineWidth += ctx.measureText(str[i]).width;
                if (lineWidth > canvasWidth) {

                    ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
                    initHeight += 30; //16为字体的高度
                    lineWidth = 0;
                    lastSubStrIndex = i;
                    titleHeight += 30;
                }
                if (i == str.length - 1) { //绘制剩余部分
                    ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);

                }
            }
            // 标题border-bottom 线距顶部距离
            initHeight = initHeight + 30;
            titleHeight = titleHeight + 10;
        }
        // var res=new Array(ctx,titleHeight);
        return titleHeight;
    },

    // 保存到系统相册
    saveShareImg(canvasToTempFilePath) {
        console.log('canvasToTempFilePath')
        let that = this;
        // 获取用户是否开启用户授权相册
        if (!that.data.openStatus) {
            wx.openSetting({
                success: (result) => {
                    console.log("result.authSettingscope.writePhotosAlbum");
                    console.log(result.authSetting["scope.writePhotosAlbum"] == true);
                    if (result) {
                        if (result.authSetting["scope.writePhotosAlbum"] == true) {
                            that.setData({
                                openStatus: true
                            });
                            wx.saveImageToPhotosAlbum({
                                filePath: canvasToTempFilePath,
                                success: function (data) {
                                    console.log("success")
                                    wx.showToast({
                                        title: '图片保存成功',
                                        icon: 'none',
                                        duration: 1000
                                    })
                                },
                                fail: function (err) {
                                    console.log("fail")
                                    wx.showToast({
                                        title: '保存失败',
                                        icon: 'none'
                                    })
                                }
                            })
                        }
                    }
                },
                fail: () => {
                    wx.getSetting({
                        success(res) {
                            // 如果没有则获取授权
                            if (!res.authSetting['scope.writePhotosAlbum']) {
                                wx.authorize({
                                    scope: 'scope.writePhotosAlbum',
                                    success() {
                                        that.setData({
                                            openStatus: true
                                        })
                                        wx.saveImageToPhotosAlbum({
                                            filePath: canvasToTempFilePath,
                                            success() {
                                                wx.showToast({
                                                    title: '图片保存成功',
                                                    icon: 'none',
                                                    duration: 1000
                                                })
                                            },
                                            fail() {
                                                wx.showToast({
                                                    title: '保存失败',
                                                    icon: 'none'
                                                })
                                            }
                                        })
                                    },
                                    fail() {
                                        // 如果用户拒绝过或没有授权，则再次打开授权窗口
                                        that.setData({
                                            openStatus: false
                                        });
                                        wx.showModal({
                                            title: '用户未授权',
                                            content: '您未开启保存图片到相册的权限，设置开启该权限？',
                                            success: function (sm) {
                                                if (sm.confirm) {
                                                    wx.openSetting()
                                                } else if (sm.cancel) {
                                                    console.log('用户点击取消')
                                                }
                                            }
                                        })

                                    }
                                })
                            } else {
                                // 有则直接保存
                                that.setData({
                                    openStatus: true
                                });
                                wx.saveImageToPhotosAlbum({
                                    filePath: canvasToTempFilePath,
                                    success() {
                                        wx.showToast({
                                            title: '图片保存成功',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                    },
                                    fail() {
                                        wx.showToast({
                                            title: '保存失败',
                                            icon: 'none'
                                        })
                                    }
                                })
                            }
                        },
                        fail(err) {
                            console.log(err)
                        }
                    })
                },
                complete: () => {

                }
            });
        } else {
            wx.getSetting({
                success(res) {
                    // 如果没有则获取授权
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success() {
                                that.setData({
                                    openStatus: true
                                })
                                wx.saveImageToPhotosAlbum({
                                    filePath: canvasToTempFilePath,
                                    success() {
                                        wx.showToast({
                                            title: '图片保存成功',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                    },
                                    fail() {
                                        wx.showToast({
                                            title: '保存失败',
                                            icon: 'none'
                                        })
                                    }
                                })
                            },
                            fail() {
                                // 如果用户拒绝过或没有授权，则再次打开授权窗口
                                that.setData({
                                    openStatus: false
                                });
                                wx.showModal({
                                    title: '用户未授权',
                                    content: '您未开启保存图片到相册的权限，设置开启该权限？',
                                    success: function (sm) {
                                        if (sm.confirm) {
                                            wx.openSetting()
                                        } else if (sm.cancel) {
                                            console.log('用户点击取消')
                                        }
                                    }
                                })
                            }
                        })
                    } else {
                        // 有则直接保存
                        console.log("有则直接保存")
                        that.setData({
                            openStatus: true
                        });
                        wx.saveImageToPhotosAlbum({
                            filePath: canvasToTempFilePath,
                            success() {
                                wx.showToast({
                                    title: '图片保存成功',
                                    icon: 'none',
                                    duration: 1000
                                })
                            },
                            fail() {
                                wx.showToast({
                                    title: '保存失败',
                                    icon: 'none'
                                })
                            }
                        })
                    }
                },
                fail(err) {
                    console.log(err)
                }
            })
        }
    },
    closeSuccessNew() {

        const that = this;
        let list = that.data.prizeList;
        let content = "";
        for (var i = 0; i < list.length; i++) {
            let prizeType = list[i].prizeTypeId;
            let status = list[i].status;
            if (prizeType == '1' && (status == '2' || status == '3' || status == '9')) { //红包
                content = '您还有红包未领取';
            }
            if (prizeType == '6' && status != '8') { //红包
                content = '您还有奖品未填写邮寄地址';
            }
            if (prizeType == '' || prizeType == undefined || prizeType == null) { //多选一
                content = '您还有奖品未挑选';
            }
        }

        if (content !== '') {
            wx.showModal({
                title: '提示',
                content: content + ',确认要关闭吗？',
                success: function (sm) {
                    if (sm.confirm) {
                        that.setData({
                            isShowPrizes: false,
                            prizeList: null,
                            qrcode: '',
                            source: ""
                        })
                        wx.removeStorageSync('isShowPrizes');
                        wx.removeStorageSync('prizeList');
                        that.queryKingVIPMember();

                    } else if (sm.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        } else {
            that.setData({
                isShowPrizes: false,
                prizeList: null,
                qrcode: '',
            })
            that.queryKingVIPMember();

        }



    },
    operaBut(e) {
        const that = this;
        let item = e.currentTarget.dataset.item; //奖项类型
        let index = e.currentTarget.dataset.index; //index
        if (item.prizeTypeId == '' || item.prizeTypeId == null || item.prizeTypeId == undefined) { //多选一
            wx.navigateTo({
                url: '../receiptInfo/receiptInfo?source=1&prizeInfo=' + JSON.stringify(item) + '&index=' + index,
            })
        }
        if (item.prizeTypeId == '6' || item.prizeTypeId == '20') { //实物奖或奖上奖
            this.data.useEntityPopupFlag = false;
            this.setData({
                isShowEntityPopup: true,
                entityData: item,
                redEnvelopes: 0
            })
            // popup.receivePrizeHand(this);
        }
        if (item.prizeTypeId == '1') { //红包
            this.prizeDraw(e)
        }
        if (item.prizeTypeId == '3') { //积分
            //存入缓存，点过立即领取
            wx.setStorageSync('goToganguo', true);
            wx.navigateToMiniProgram({
                appId: api.thirdAppId,
                path: 'pages/home/home',
                envVersion: getApp().globalData.ganguoAppidStyle,
                success() {
                    //存入缓存，点过立即领取
                    wx.setStorageSync('goToganguo', true);
                    that.setData({
                        'goToganguo': true
                    })
                }
            })
        }

    },
    queryJDticketInfo(prizeOrderId, fticketno, status, index) {
        this.isLoading(true, "正在加载...")
        const that = this;
        netWork.POST('QueryTicketInfo', {
            data: {
                prizeOrderId: prizeOrderId,
                fticketno: fticketno
            },
            success: function (res) {
                that.isLoading(false)
                if (res.data.retCode == undefined) {
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                    })
                }
                if (res.data.retCode == "0000") { //成功
                    if (res.data.data != null && res.data.data != '') {
                        that.setData({
                            ticket: res.data.data,
                            isShowQRcode: true,
                            qrcodeBigURL: that.drawImg(res.data.data.FTicketNo)
                        })
                    }
                    if (res.data.data.FSource == '001' && status != 13) { //餐饮
                        that.subscribeMessage(prizeOrderId, index, fticketno);
                    }


                } else {
                    //跳转温馨提示页面
                    wx.redirectTo({
                        url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                    })

                }
            },
            fail: function () {
                that.isLoading(false)
                //跳转温馨提示页面
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
        })
    },
    //生成二维码
    drawImg: function (ticketNo) {
        var imgData = QR.drawImg(ticketNo, {
            typeNumber: 4,
            errorCorrectLevel: 'M',
            size: 500
        })
        return imgData;
    },
    // 订阅信息的下发授权
    subscribeMessageNew: function (prizeOrderId, index, fticketNo, status) {
        let that = this;
        let error_url = '../prompt/prompt';
        try {
            if (status != 10 && status != 11 && status != 13) {
                //请求立即使用接口
                netWork.POST('ticketUsed', {
                    data: {
                        userId: wx.getStorageSync('userId'),
                        prizeOrderId: prizeOrderId,
                        ticketNo: Base64.encode(fticketNo).replace(/=/g, "")
                    },
                    success: function (res) {
                        if(res.data.retCode == "10029"){
                            wx.redirectTo({
                                url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                            }) 
                        }

                    },
                    fail: function (res) {

                    }
                });
            }
            if (status == 13) {
                wx.navigateTo({
                    url: '../../commonPage/ticket/ticket?fticketNo=' + encodeURIComponent(fticketNo)
                })
                return;
            }
            wx.getSetting({
                withSubscriptions: true, //这句怎么无效
                success(e) {
                    try {
                        var mainSwitch = e.subscriptionsSetting.mainSwitch;
                        if (mainSwitch) {
                            //true，总开关订阅消息
                            console.log(e.subscriptionsSetting.itemSettings);
                            if (typeof e.subscriptionsSetting.itemSettings != 'undefined') { //
                                var size = 0;
                                var key;
                                var obj = e.subscriptionsSetting.itemSettings;
                                for (key in obj) { //obj中存在几个关键字
                                    if (obj.hasOwnProperty(key))
                                        size++;
                                }
                                if (size != 2) {
                                    that.setData({
                                        isSubMsg: true
                                    })
                                }
                            } else { //没有该节点弹出
                                that.setData({
                                    isSubMsg: true
                                })
                            }
                        }
                    } catch (e1) {

                    }

                }
            })
            wx.requestSubscribeMessage({
                tmplIds: ['KyJMnBXyKJ1nrCQiMfRDCZnT-JLSMVo1cz98jC85cKg', 'mLYNe8uqrdlB28ymi8g70TMXtaZ-Apc2ZIf_6gbudco', 'WNN9vqU-qSPjlpN8kj8J5OMIbqXKbSkqGN3YvAu_w0A'],
                success(res) {
                    var subscriptionData = [];
                    for (let key in res) {
                        if (key !== "errMsg" && key !== "errorCode") {
                            let obj = {
                                template_id: key,
                                status: res[key]
                            };
                        }
                        console.log(res)
                        log.info(res);
                        that.setData({
                            isSubMsg: false
                        })
                    }
                    wx.navigateTo({
                        url: '../../commonPage/ticket/ticket?fticketNo=' + encodeURIComponent(fticketNo)
                    })

                },
                fail(res) {
                    console.log(res);
                    that.setData({
                        isSubMsg: false
                    })
                    wx.navigateTo({
                        url: '../../commonPage/ticket/ticket?fticketNo=' + encodeURIComponent(fticketNo)
                    })
                }
            })
        } catch (err) { // 当前微信版本不支持订阅信息
            console.error("subscribeMessage-err", err);
        }
    },
    // 订阅信息的下发授权
    subscribeMessage: function (prizeOrderId, index, ticketNo) {
        let that = this;
        try {
            //请求立即使用接口
            netWork.POST('ticketUsed', {
                data: {
                    userId: wx.getStorageSync('userId'),
                    prizeOrderId: prizeOrderId,
                    ticketNo: Base64.encode(ticketNo).replace(/=/g, "")
                },
                success: function (res) {
                    if (res.data.retCode == "0000") {
                        //更新状态为13-核销中
                        that.setData({
                            ['prizeList[' + index + '].status']: 13
                        })
                    }

                },
                fail: function (res) {

                }
            });
            wx.getSetting({
                withSubscriptions: true, //这句怎么无效
                success(e) {
                    try {
                        var mainSwitch = e.subscriptionsSetting.mainSwitch;
                        if (mainSwitch) {
                            //true，总开关订阅消息
                            console.log(e.subscriptionsSetting.itemSettings);
                            if (typeof e.subscriptionsSetting.itemSettings != 'undefined') { //
                                var size = 0;
                                var key;
                                var obj = e.subscriptionsSetting.itemSettings;
                                for (key in obj) { //obj中存在几个关键字
                                    if (obj.hasOwnProperty(key))
                                        size++;
                                }
                                if (size != 2) {
                                    that.setData({
                                        isSubMsg: true
                                    })
                                }
                            } else { //没有该节点弹出
                                that.setData({
                                    isSubMsg: true
                                })
                            }
                        }
                    } catch (e1) {

                    }

                }
            })
            wx.requestSubscribeMessage({
                tmplIds: ['KyJMnBXyKJ1nrCQiMfRDCZnT-JLSMVo1cz98jC85cKg', 'mLYNe8uqrdlB28ymi8g70TMXtaZ-Apc2ZIf_6gbudco', 'WNN9vqU-qSPjlpN8kj8J5OMIbqXKbSkqGN3YvAu_w0A'],
                success(res) {
                    var subscriptionData = [];
                    for (let key in res) {
                        if (key !== "errMsg" && key !== "errorCode") {
                            let obj = {
                                template_id: key,
                                status: res[key]
                            };
                        }
                        console.log(res)
                        log.info(res);
                        that.setData({
                            isSubMsg: false
                        })
                    }


                },
                fail(res) {
                    console.log(res);
                    that.setData({
                        isSubMsg: false
                    })
                }
            })
        } catch (err) { // 当前微信版本不支持订阅信息
            console.error("subscribeMessage-err", err);
        }
    },
    //优惠券立即使用
    async ticketDraw(event) {

        //防止重复点击或者点击过快
        console.log("点击了");
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 2000); //2秒内不能重复点击
        }
        let prizeInfo = event.currentTarget.dataset.item;
        let index = event.currentTarget.dataset.index;
        this.setData({
            ticketName: prizeInfo.prizeName
        })
        const that = this;
        console.log(prizeInfo)
        //判断是否是有赞优惠券
        if (prizeInfo.prizeTypeId == 12) {
            wx.navigateToMiniProgram({
                appId: 'wx785770f82ffbd282',
                path: prizeInfo.prizeValue
            })
            return;
        }
        if (prizeInfo.prizeTypeId == 16 || prizeInfo.prizeTypeId == 17) { //16,17
            if (prizeInfo.fticketNo == '' || prizeInfo.fticketNo == null) {
                wx.redirectTo({
                    url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=优惠券编码为空',
                })
                return;
            }
            that.subscribeMessageNew(prizeInfo.prizeOrderId, index, prizeInfo.fticketNo, prizeInfo.status);
            return;
        }
        //状态=2,需要同步
        if (prizeInfo.status == '2' || prizeInfo.fticketNo == '' || prizeInfo.fticketNo == null) {
            netWork.POST('getTicketNo', {
                data: {
                    prizeOrderId: prizeInfo.prizeOrderId
                },
                success: function (res) {
                    if (res.data.retCode == undefined) {
                        wx.redirectTo({
                            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                        })
                    }
                    if (res.data.retCode == "0000") {
                        //成功，调用查询礼券详情接口
                        if (res.data.fticketNo == '' || res.data.fticketNo == null) { //礼券为空
                            wx.showToast({
                                title: '优惠券正在发放',
                                icon: 'error',
                                duration: 3000
                            })
                            return;
                        } else { //不为空查询金蝶详情接口
                            that.queryJDticketInfo(prizeInfo.prizeOrderId, res.data.fticketNo, prizeInfo.status, index);
                        }
                    } else {
                        wx.showToast({
                            title: '优惠券正在发放',
                            icon: 'error',
                            duration: 3000
                        })

                    }
                },
                fail: function () {
                    wx.showToast({
                        title: '优惠券正在发放',
                        icon: 'error',
                        duration: 3000
                    })
                }
            })
        } else { //不需要同步，
            let ticket = await that.queryJDticketInfo(prizeInfo.prizeOrderId, prizeInfo.fticketNo, prizeInfo.status, index);

        }

    },
    async closeTicket() {
        this.setData({
            isShowQRcode: false,
            ticket: "",
            qrcodeBigURL: ""
        })


    },
    /**
     * 红包兑奖
     * @param {*} event 
     */
    prizeDraw: function (e) {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        let prizeInfo = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        if (prizeInfo.status == '8') {
            return;
        }
        api.showLoading('正在领取...');
        const that = this;
        log.info('[prizeRecord]--->[receiveWxRedBag]')

        //兑奖
        netWork.POST('receiveWxRedBag', {
            data: {
                userId: wx.getStorageSync('userId'),
                prizeOrderId: prizeInfo.prizeOrderId,
                prizeId: prizeInfo.prizeId,
                positioningStyle: wx.getStorageSync('positioningStyle') == '' ? '0' : wx.getStorageSync('positioningStyle'),
                positioningType: wx.getStorageSync('positioningType') == '' ? '-1' : wx.getStorageSync('positioningType'),
                latitude: wx.getStorageSync('latitude'),
                longitude: wx.getStorageSync('longitude'),
                speed: wx.getStorageSync('speed'),
                accuracy: wx.getStorageSync('accuracy'),
                source: 1, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
            },
            success: function (res) {
                api.cancelLoading();
                if (res.data.retCode == undefined) {
                    setTimeout(function () {
                        wx.showToast({
                            title: '领取失败',
                            icon: 'error',
                            duration: 3000
                        })
                    }, 200);

                }
                if (res.data.retCode == "0000") {
                    setTimeout(function () {
                        wx.showToast({
                            title: '领取成功',
                            icon: 'success',
                            duration: 3000
                        })
                    }, 200);

                    //更新该prizeOrderid对应的状态
                    that.setData({
                        ['prizeList[' + index + '].status']: 8
                    })
                    //更新缓存中的prizeList
                    wx.setStorageSync('prizeList', that.data.prizeList);

                } else {
                    setTimeout(function () {
                        wx.showToast({
                            title: '领取失败',
                            icon: 'error',
                            duration: 3000
                        })
                    }, 200);

                }

            },
            fail: function () {
                wx.showToast({
                    title: '领取失败',
                    icon: 'error',
                    duration: 3000
                })
            }
        });


    },
    //获取地理位置组参加密跳转博饼H5
    async enterPancake(e) {
        let index = e.currentTarget.dataset.index;
        let url = await bobing.getBobingKey(this, netWork, this.data.prizeList[index].prizeValue);
        if (url) {
            let replace = url.replace(/\+/g, '%2B');
            getApp().globalData.bobingPathAndParams = replace;
            wx.navigateTo({
                url: '/pages/jingdianPage/bobingWebview/bobingWebview'
            })
        }
    },
    /**
     * 打开设置
     */
    openSetting() {
        this.setData({
            isShowModalAuth: false
        })
        api.putOpenSetting();
    },
    updateOrder: function (event) {
        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 3000); //3秒内不能重复点击
        }
        let index = event.currentTarget.dataset.index;
        let prizeInfo = event.currentTarget.dataset.prizeinfo;
        let productType = event.currentTarget.dataset.prizeinfo.productType;
        // if (prizeInfo.materialInfo.receiveExpressOrderCode != null) { //查看物流
        //   this.setData({
        //     isShowModal: true,
        //     ani: 0,
        //     materialInfo: prizeInfo.materialInfo,
        //     productType: prizeInfo.productType
        //   })
        //   this.queryWL();
        // } else {  
        const that = this;

        wx.showModal({
            title: '提示',
            content: '确认收到货了吗？',
            success: function (sm) {
                if (sm.confirm) {
                    that.isLoading(true, "加载中...");
                    let error_url = '../prompt/prompt';

                    //兑奖
                    netWork.POST('confirmMatter', {
                        data: {
                            userId: wx.getStorageSync('userId'),
                            prizeOrderId: prizeInfo.prizeOrderId,

                        },
                        success: function (res) {
                            that.isLoading(false)
                            if (res.data.retCode == undefined) {
                                wx.redirectTo({
                                    url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                                })
                            }
                            if (res.data.retCode == "0000") {
                                wx.showToast({
                                    title: '操作成功',
                                    icon: 'success'
                                })
                                //更新该prizeOrderid对应的状态
                                that.data.prizeList[index].status = '14';
                                that.setData({
                                    prizeList: that.data.prizeList
                                })
                                wx.setStorageSync('prizeList', that.data.prizeList)
                            } else {
                                if(res.data.retCode == "10029"){
                                    wx.redirectTo({
                                        url: error_url + '?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
                                    }) 
                                }else{
                                    wx.showToast({
                                        title: '操作失败',
                                        icon: 'error'
                                    })
                                }
                            }

                        },
                        fail: function () {
                            that.isLoading(false)
                            wx.showToast({
                                title: '操作失败',
                                icon: 'error'
                            })
                        }
                    });


                } else if (sm.cancel) {
                    return;
                }
            }
        })
    },
    //点击选择城市按钮显示picker-view
    translate: function (e) {
        console.log('点击了')
        model.animationEvents(this, 0, true, 400);
    },
    //城市隐藏picker-view
    hiddenFloatView: function (e) {
        model.animationEvents(this, 200, false, 400);
        if (e.target.dataset.id == '555') {
            return;
        }
        if (this.data.address == '请选择省/市/区' || JSON.stringify(addressInfo) == '{}' || (this.data.item.value[0] == 0 && this.data.item.value[1] == 0 && this.data.item.value[2] == 0)) {
            addressInfo = {
                "receiveProvinceId": '110000',
                "receiveCityId": '110100',
                "receivceDistrictId": '110101',
                "receiveProvinceName": '北京市',
                "receiveCityName": '北京市',
                "receiveDistrictName": '东城区'
            };

        }
        this.setData({
            address: addressInfo.receiveProvinceName + ' ' + addressInfo.receiveCityName + ' ' + addressInfo.receiveDistrictName,
        })
        // popup.receivePrizeHand(this);
    },
    //城市滑动事件
    bindChange: function (e) {
        model.updateAreaData(this, 1, e);
        item = this.data.item;
        addressInfo = {
            "receiveProvinceId": item.provinces[item.value[0]].id,
            "receiveCityId": item.citys[item.value[1]].id,
            "receivceDistrictId": item.countys[item.value[2]].id,
            "receiveProvinceName": item.provinces[item.value[0]].name,
            "receiveCityName": item.citys[item.value[1]].name,
            "receiveDistrictName": item.countys[item.value[2]].name
        };
    },
    //表单提交按钮,校验
    formSubmit: function (e) {
        //防止重复点击或者点击过快
        console.log("点击了");
        if (!isClick) {
            console.log("重复返回~");
            return;
        }
        if (isClick) {
            isClick = false;
            //定时器
            setTimeout(function () {
                isClick = true;
            }, 5000); //3秒内不能重复点击
        }
        let userName = e.detail.value.userName;
        let phone = e.detail.value.phone;
        let detailAddress = e.detail.value.detailAddress;
        if (userName.trim() == "") {
            wx.showToast({
                title: '请输入收件人姓名',
                icon: 'none'
            })
            return;
        }
        if (userName.length > 20) {
            wx.showToast({
                title: '收件人姓名不能超过20个文字',
                icon: 'none'
            })
            return;
        }
        if (phone.trim() == "") {
            wx.showToast({
                title: '请输入手机号码',
                icon: 'none'
            })
            return;
        }

        let a = /^1\d{10}$/;
        if (!a.test(phone)) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none'
            })
            return;
        }
        if (this.data.address == '请选择地区') {
            wx.showToast({
                title: '请选择地区',
                icon: 'none'
            })
            return;
        }
        if (detailAddress.trim() == "") {
            wx.showToast({
                title: '请输入详细地址',
                icon: 'none'
            })
            return;
        }
        if (detailAddress.length > 60) {
            wx.showToast({
                title: '详细地址不能超过60个文字',
                icon: 'none'
            })
            return;
        }
        this.setData({
            formValue: e.detail.value,
            addressMsg: detailAddress
        })
        let materialInfo = {};
        materialInfo['receiveProvinceId'] = addressInfo.receiveProvinceId;
        materialInfo['receiveCityId'] = addressInfo.receiveCityId;
        materialInfo['receivceDistrictId'] = addressInfo.receivceDistrictId;
        materialInfo['receiveProvinceName'] = addressInfo.receiveProvinceName;
        materialInfo['receiveCityName'] = addressInfo.receiveCityName;
        materialInfo['receiveDistrictName'] = addressInfo.receiveDistrictName;
        materialInfo['receiveName'] = userName;
        materialInfo['receivePhone'] = phone;
        materialInfo['receiveAddress'] = detailAddress;
        console.info(materialInfo);
        wx.setStorageSync('materialInfo', materialInfo)
        if (this.data.useEntityPopupFlag) {
            popup.receiveBenefitCard(this, netWork, addressInfo, getApp().globalData.benefitCardSpeedData.prizeOrderId);
        } else {
            popup.revicePrize(this, netWork, addressInfo);
        }
    },
    //关闭实物弹窗
    async closeEntityPopup(e) {
        this.setData({
            isShowEntityPopup: false
        })
        let id = "";
        if (this.data.useEntityPopupFlag) {
            id = getApp().globalData.benefitCardSpeedData.prizeOrderId;
        } else {
            let item = e.currentTarget.dataset.item;
            id = item.prizeOrderId;
            popup.setHandFlag(this);
        }
        let flag = await isShowReminderOfExpired(id);
        if (flag) {
            requestSubscribeMessage(id);
        }
    },
    //实物弹窗判断姓名输入框是否有值显示隐藏小手
    userName(e) {
        popup.setMaterialInfoAndIsHand(1, this, e.detail.value);
    },
    userPhone(e) {
        popup.setMaterialInfoAndIsHand(2, this, e.detail.value);
    },
    userDetailAddress(e) {
        popup.setMaterialInfoAndIsHand(3, this, e.detail.value);
    },
    //兑换券和买赠卷跳转详情页
    coupon() {
        this.setData({
            isShowCouponPopup: false
        })
        let index = 0;
        let item = {};
        for (let i = 0; i < this.data.prizeList.length; i++) {
            if (this.data.prizeList[i].prizeOrderId == this.data.couponPrizeInfo.prizeOrderId) {
                index = i;
                item = this.data.prizeList[i];
                break;
            }
        }
        this.subscribeMessageNew(item.prizeOrderId, index, item.fticketNo, item.status);
    },
    //关闭卷弹窗
    closeCouponPopup() {
        this.setData({
            isShowCouponPopup: false
        })
        // popup.setHandFlag(this);
    },
    //关闭实物领取成功提示
    closeEntityTips() {
        this.setData({
            isShowEntityTips: false
        })
        //   popup.setHandFlag(this);
    },
    //权益卡跳转详情页
    async benefitCardDetails(e) {
        let item = e.currentTarget.dataset.item; //奖项类型
        // this.data.handPrizeId = item.id;
        let flag = await isShowReminderOfExpired(item.prizeOrderId);
        if (flag) {
            requestSubscribeMessage(item.prizeOrderId);
        }
        wx.navigateTo({
            url: '/pages/commonPage/benefitCardDetails/benefitCardDetails?prizeOrderId=' + item.prizeOrderId
        })
    },
    speedReceiveEntity() {
        this.data.useEntityPopupFlag = true;
        //红包信息
        // let redEnvelopes = 0;
        // for (let item of this.data.prizeList) {
        //     if (item.prizeTypeId == 1 && item.status != '1' && item.status != '3' && item.status != '9') {
        //         if(item.doublePrizeAmount){
        //             redEnvelopes = item.doublePrizeAmount/100;
        //         }else{
        //             redEnvelopes = item.prizeAmount/100;
        //         }
        //     }
        // }
        let entityData = {
            prizeUrl: getApp().globalData.benefitCardSpeedData.subjoinPrizeUrl,
            prizeName: getApp().globalData.benefitCardSpeedData.subjoinPrizeName
        }
        this.setData({
            isShowEntityPopup: true,
            entityData,
            redEnvelopes:0
        })
        popup.receivePrizeHand(this)
    }
})